// @Desc:
// @CreateTime: 2020/11/3
package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"gorm.io/gorm"
	"mycrm.com/config"
	"mycrm.com/module"
	"mycrm.com/module/towx"
	mlog "mycrm.com/mylog"
)

type Wx struct {
	AppId     string
	AppSecret string
	Host      string
}

// 初始化
func NewWx() *Wx {
	isProduct := config.Configs.LogConf.IsProduction
	if isProduct {
		return &Wx{
			AppId:     "",
			AppSecret: "",
			Host:      "",
		}
	} else { // 测试环境
		return &Wx{
			AppId:     "wxd8a2f86f78f1a895",
			AppSecret: "75dffa1dca32ec3f61c8fe7d06b954bb",
			Host:      "https://api.weixin.qq.com",
		}
	}
}

// 获取 access_token
func (w *Wx) GetAccessToken() (bool, string) {
	// GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
	// 首先查询下本地是否存在并有效
	var tokenInfo towx.ToWx
	module.Db.Find(&tokenInfo, "id = 1")
	okTokenTime := time.Now().Unix() - 60
	if tokenInfo.ExpiresIn <= okTokenTime {
		return true, tokenInfo.AccessToken
	}
	client := &http.Client{
		Timeout: time.Second * 10,
	}
	url := fmt.Sprintf("%s/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", w.Host, w.AppId, w.AppSecret)
	resp, err := client.Get(url)
	if err != nil {
		mlog.Log.Error("get access_token is failed, err: ", err)
	}
	body, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	var json2towx towx.ToWx
	if err := json.Unmarshal(body, &json2towx); err != nil {
		mlog.Log.Error("json.Unmarshal(body, &towxObj) is failed, err: ", err)
		return false, ""
	}
	mlog.Log.Info("respBody: ", json2towx)
	// 把 expires_in 处理为实际时间
	json2towx.ExpiresIn += time.Now().Unix()
	// 用 id = 1 进行保存
	var towxInfo towx.ToWx
	if err := module.Db.Model(&towx.ToWx{}).Where("id = 1").First(&towxInfo).Error; err == gorm.ErrRecordNotFound {
		module.Db.Create(&json2towx)
	} else {
		module.Db.Where("id = 1").Updates(&json2towx)
	}
	return true, json2towx.AccessToken
}

// 语言转文本信息
// format: 格式,  mediaId: 媒体id
func (w *Wx) Voice2Text(format string, mediaId int64) {
	// POST http://api.weixin.qq.com/cgi-bin/media/voice/addvoicetorecofortext?access_token=ACCESS_TOKEN&format=&voice_id=xxxxxx&lang=zh_CN
	// client := &http.Client{
	//     Timeout: time.Second * 10,
	// }
	// _, token := w.GetAccessToken()
	// url := fmt.Sprintf("%s/cgi-bin/media/voice/addvoicetorecofortext?access_token=%s&format=%s&voice_id=%s&lang=zh_CN", w.Host, token, wxReqMsg.Format, wxReqMsg.MediaId)
	// resp, err := client.Post()
	// if err != nil {
	//     mlog.Log.Error("get access_token is failed, err: ", err)
	// }
}
